<?php

namespace app\store\controller\market;

use app\store\controller\BaseController;
use app\store\model\Coupon;
use app\store\service\CouponService;
use think\exception\ValidateException;
use think\facade\View;

class CouponController extends BaseController
{
    public function index()
    {   
        $param = $this->request->param();

        $couponService = new CouponService();
        $list = $couponService->getCouponList($param);

        return View::fetch('',['list' => $list]);
    }
    
    public function create()
    {

        return View::fetch();
    }


    public function option()
    {
        $param = $this->request->param();

        $couponService = new CouponService();

        $list = $couponService->getCouponList($param);

        View::engine()->layout(false);

        return View::fetch('',['list' => $list]);
    }

    public function edit()
    {   
        $id = $this->request->get('id/d');

        $couponService = new CouponService();
        $row = $couponService->findCoupon($id);

        return View::fetch('',['row' => $row]);
    }

    public function save()
    {
        $param = $this->request->post();
        
        try{
            validate('CouponValidate')->check($param);
        }catch (ValidateException $e){
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
        
        $param['store_id'] = session('store_id');

        $resulet =  CouponService::saveCoupon($param);

        return  $resulet ? json(['code' => 1, 'msg' => '保存成功!']) : json(['code' => 0, 'msg' => '保存失败!']);
        
    }

    public function update()
    {
        $param = $this->request->post();
        
        try{
            validate('CouponValidate.edit')->check($param);
        }catch (ValidateException $e){
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        $resulet =  CouponService::updateCoupon($param);

        return $resulet ? json(['code' => 1, 'msg' => '更新成功!']) : json(['code' => 0, 'msg' => '更新失败!']);
    }


    public function delete()
    {
        $id = $this->request->get('id/d');

        $res = Coupon::destroy($id);

        return  $res ? json(['code' => 1,'msg' => '删除成功!']) : json(['code' => 0, 'msg' => '删除失败']);

    }
}